<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">预存管理</h1>
      <div class="header-controls">
        <div class="total-amount">
          预存总金额：<span class="amount">¥{{ totalAmount }}</span>
        </div>
        <el-input
          v-model="searchForm.name"
          placeholder="缴费人姓名"
          style="width: 200px; margin-left: 16px; margin-right: 10px"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 操作按钮区域 -->
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button
            type="danger"
            plain
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            批量删除 ({{ selectedRows.length }})
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-button @click="handleRefresh">刷新</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="缴费人" width="120" />
        <el-table-column
          prop="payerType"
          label="类型"
          width="90"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getPayerTypeTag(row.payerType)">{{
              getPayerTypeText(row.payerType)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="phone"
          label="联系电话"
          width="130"
          show-overflow-tooltip
        />
        <el-table-column
          prop="email"
          label="邮箱"
          width="160"
          show-overflow-tooltip
        />
        <el-table-column prop="amount" label="当前余额" width="100">
          <template #default="{ row }">¥{{ row.amount }}</template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" link @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getPredepositList,
  getPredepositTotalAmount,
  deletePredeposit
} from "@/api/predeposit";
import type { PredepositListItem } from "@/api/predeposit";

defineOptions({ name: "Predeposit" });

// 响应式数据
const loading = ref(false);
const tableData = ref<PredepositListItem[]>([]);
const selectedRows = ref<PredepositListItem[]>([]);
const total = ref(0);
const totalAmount = ref(0);

// 搜索表单
const searchForm = reactive({
  name: ""
});

// 分页（后端从0开始，这里UI从1开始展示）
const pagination = reactive({
  page: 1,
  limit: 10
});

// 类型显示
const getPayerTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: "业主",
    2: "租房人员",
    3: "客户"
  };
  return typeMap[type] || "未知";
};
const getPayerTypeTag = (
  type: number
): "success" | "warning" | "info" | "primary" | "danger" => {
  const tagMap: Record<
    number,
    "success" | "warning" | "info" | "primary" | "danger"
  > = {
    1: "success",
    2: "warning",
    3: "info"
  };
  return tagMap[type] || "info";
};

// 获取总金额
const fetchTotalAmount = async () => {
  try {
    const res = await getPredepositTotalAmount();
    if (res.code === 0) totalAmount.value = res.data ?? 0;
  } catch (e) {
    // 忽略错误，仅提示
    ElMessage.error("获取总金额失败");
  }
};

// 获取列表
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page - 1,
      limit: pagination.limit,
      name: searchForm.name
    };
    const res = await getPredepositList(params);
    if (res.code === 0) {
      tableData.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.message || "获取数据失败");
    }
  } catch (e) {
    ElMessage.error("获取数据失败");
    console.error(e);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchData();
};

// 重置
const handleReset = () => {
  searchForm.name = "";
  pagination.page = 1;
  fetchData();
};

// 刷新
const handleRefresh = () => {
  fetchData();
  fetchTotalAmount();
};

// 选择变化
const handleSelectionChange = (selection: PredepositListItem[]) => {
  selectedRows.value = selection;
};

// 删除单条
const handleDelete = async (row: PredepositListItem) => {
  if (!row.id) return;
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${row.name} 的预存记录吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    loading.value = true;
    const res = await deletePredeposit([row.id]);
    if (res.code === 0) {
      ElMessage.success("删除成功");
      fetchData();
      fetchTotalAmount();
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch {
    // 取消
  } finally {
    loading.value = false;
  }
};

// 批量删除
const handleBatchDelete = async () => {
  const ids = selectedRows.value.map(i => i.id!).filter(Boolean) as number[];
  if (ids.length === 0) {
    ElMessage.warning("请选择要删除的记录");
    return;
  }
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${ids.length} 条预存记录吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    loading.value = true;
    const res = await deletePredeposit(ids);
    if (res.code === 0) {
      ElMessage.success("删除成功");
      selectedRows.value = [];
      fetchData();
      fetchTotalAmount();
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch {
    // 取消
  } finally {
    loading.value = false;
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchData();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchData();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
  fetchTotalAmount();
});
</script>

<style scoped>
.main {
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  margin-bottom: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.total-amount {
  font-size: 14px;
  color: #606266;
}
.total-amount .amount {
  font-weight: 600;
  color: #f56c6c;
  margin-left: 4px;
}

.content-area {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
  min-height: 400px;
  padding: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.toolbar-left {
  display: flex;
  gap: 10px;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 6px;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: center;
}
</style>
